<?php
/**
 * Geneone: Content Management Framework
 * Discussion Object View
 *
 * http://geneone.neondragon.net/
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
require_once ("Gene/Object/View.php");

class Gene_Object_View_Discussion extends Gene_Object_View {
	/**
	 * Class Constructor
	 *
	 * @var object $model Gene_Object_Model object
	 */
	function Gene_Object_View_Discussion(&$model) {
		$this->model =& $model;
	}
	
	/**
	 * Show this object. Returns HTML output code for object.
	 *
	 * @var array $actions Additional Arguments
	 *
	 * @return string HTML output for object.
	 */
	function view($actions=array()) {
		$tpl =& Gene::getTemplate();
		$user =& Gene::getUser();
		
		/* Handle /view/unread */
		if (isset($actions[2]) && $actions[2] == "unread") {
			$hasRead = $this->model->hasRead();
			
			if (!$hasRead) {
				header ("Location: ".Gene::makeLink(Gene::objectID($this->model)));
			} else {
				$this->model->enablePaging(1);
				$this->model->setPageNumber($hasRead);
				$childs = $this->model->getChilds();
				
				$url = Gene::makeLink(Gene::objectID($this->model));
				$parsed = parse_url($url);
				
				if (count($childs)) {
					$object = $childs[0];
					
					if (ceil($hasRead/25)) {
						if (isset($parsed['query'])) {
							$url .= "&page=".ceil($hasRead/25);
						} else {
							$url .= "?page=".ceil($hasRead/25);
						}
					}

					header ("Location: ".$url."#comment".$object['object_id']);
				} else {
					header ("Location: ".$url);
				}
			}
			exit();
		} else if (isset($actions[2]) && $actions[2] == "report" && $user->getUserId()) {
			$tpl =& Gene::getTemplate();
			
			/* Parents */
			$parents = $this->model->getParents();
			$tpl->assign ("parents", $parents);
			
			$report =& $this->model->getReport();
			
			$info = $this->model->get();
			if ($reportinfo = $report->get()) {
				$tpl->assign ("reported", true);
				$tpl->assign ("report", $reportinfo);
			}
			
			$tpl->assign ("object", $info);
			
			if ($_SERVER['REQUEST_METHOD'] == "POST") {
				$remove = Gene_Request::getBoolean("remove", GENE_REQUEST_POST);
				if ($remove) {
					$report->remove();
					header ("Location: ".Gene::makeLink($info));
					exit();
				} else {
					$type = Gene_Request::getInteger("complaint", GENE_REQUEST_POST);
					$comments = Gene_Request::getString("additional", GENE_REQUEST_POST);
					
					if ($report->set($type, $comments)) {
						header ("Location: ".Gene::makeLink($info));
						exit();
					} else {
						$tpl->assign ("errormsg", "There was an error reporting this comment.");
					}
				}
			}
			
			$tpl->append ("stylesheets", "discussion");
			
			return $tpl->fetch("objects/discussion/view_report");
		} else {
			/* General Object Information */
			$info = $this->model->get();
			
			$extra = $this->model->getAdditionalInfo(Gene::tableName("discussions"));
			$tpl->assign ("extra", $extra);
			
			if (!$info['owner_id']) {
				$guest = $this->model->getAdditionalInfo(Gene::tableName("object_guests"));
				$info = array_merge($guest, $info);
			}
			

			$tpl->assign ("pagetitle", $info['title']);
			$tpl->assignRef ("object", $info);
			
			/* Parents */
			$parents = $this->model->getParents();
			$tpl->assign ("parents", $parents);
			
			$i = count($parents)-1;
			$tpl->assign ("parent", $parents[$i]);
			
			/* Taxonomy & Similar Entries */
			$taxonomy =& $this->model->getTaxonomyEntry($info['parent']);
			$tpl->assign ("tags", $taxonomy->getAll());
			$tpl->assign ("similar", $taxonomy->findSimilar());
			
			// User Forum Tags
			$parent =& Gene_Object::get($info['parent']);
			$userforumtag =& $parent->getUserTaxonomySet();
			$tpl->assign ("userforumtags", $userforumtag->getLabels());
			
			// Get User Tags for this discussion
			$usertag =& $this->model->getUserTaxonomyEntry($info['parent']);
			$tpl->assign ("usertags", $usertag->getAll());
			
			$tpl->append ("portlets", "discussion");
			
			/* Read Status */
			$hasRead = $this->model->hasRead();
			
			/* Get Discussions */
			$this->model->enablePaging(25);
			$tpl->assign ("perpage", 25);
			
			$numpages = $this->model->getNumPages();
			$page = Gene_Request::getInteger("page", GENE_REQUEST_GET);
			if (!$page OR $page > $numpages) {
				$page = 1;
			}
			
			$this->model->setPageNumber($page);
			$tpl->assign ("pagenum", $page);
			$tpl->assign ("numpages", $this->model->getNumPages());
			
			$childs = $this->model->getChilds(array("tables" => Gene::tableName("object_guests")));
			if ($user->getUserId()) {
				foreach ($childs as $j => $k) {
					if ((($page-1)*25)+$j+2 > $hasRead) {
						$childs[$j]['unread'] = true;
					}
				}
			}
			
			$tpl->assign ("childs", $childs);
			
			if ($user->getUserId() && !$hasRead) {
				$info['unread'] = true;
			}
			
			if (($page-1)*25+count($childs)+1 > $hasRead) {
				$this->model->markRead(($page-1)*25+count($childs)+1);
			}
			
			if ($user->getUserId()) {
				if ($centre = $this->model->getCentreId()) {
					$parent = Gene_Object::get($centre);
					$tpl->assign ("myforums", $parent->getMyForums());
				}
			}
			
			/* Discussion Javascript */
			$tpl->append ("scripts", "discussion");
			
			return $tpl->fetch("objects/discussion/view");
		}
	}
	
	/**
	 * Callback function to specify object specific edit actions.
	 */
	function getCustomEditActions() {
		$user =& Gene::getUser();
		$info =& $this->model->get();
		
		$this->editActions['moderate'] = "Moderate";
		
		if ($info['parent'] != "-1" && $user->hasPermission("namespaces.object.move.discussion") && !$this->model->isStandalone()) {
			$this->editActions['move'] = "Move";
		}
	}
	
	/**
	 * Callback function to call specific edit action
	 */
	function callCustomEditAction($action) {
		$tpl =& Gene::getTemplate();
		
		$info = $this->model->get();
		
		$extra = $this->model->getAdditionalInfo(Gene::tableName("discussions"));
		$tpl->assign ("extra", $extra);
		
		if ($action == "moderate") {
			if ($_SERVER['REQUEST_METHOD'] == "POST") {
				$moderation = Gene_Request::getString("moderation", GENE_REQUEST_POST);
				if (in_array($moderation, array("lock", "sticky")) AND $this->model->canModerate()) {
					if ($moderation == "lock") {
						if ($extra['readonly']) {
							$this->model->setLocked(false);
						} else {
							$this->model->setLocked(true);
						}
					} else if ($moderation == "sticky") {
						if ($extra['priority'] == 1) {
							$this->model->setSticky(true);
						} else {
							$this->model->setSticky(false);
						}
					}
					
					header ("Location: ".Gene::makeLink(Gene::objectID($info['object_id'])));
					exit();
				}
			}
			
			return $tpl->fetch ("objects/discussion/edit/moderate");
		} else if ($action == "move") {
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				$target = Gene_Request::getInteger("forum", GENE_REQUEST_POST);
				
				$targetobj =& Gene_Object::get($target);
				if ($targetobj && $targetobj->canModerate()) {
					$message = Gene_Request::getString ("movemessage", GENE_REQUEST_POST);
					$ghost = Gene_Request::getBoolean ("ghost", GENE_REQUEST_POST);
					$permissions = Gene_Request::getBoolean ("permissions", GENE_REQUEST_POST);
					
					if ($message) {
						$comment = Gene_Object::create("discussioncomment", "", "", $message, $this->model);
					}
					
					if (isset($comment) && PEAR::isError($comment)) {
						$tpl->assign ("errormsg", $comment->getMessage());
					} else {
						$m = $this->model->move($targetobj, $ghost, $permissions);
						if (PEAR::isError($m)) {
							$tpl->assign ("errormsg", $m->getMessage());
						} else {
							header ("Location: ".Gene::makeLink(Gene::objectID($this->model)));
							exit();
						}
					}
				} else {
					$tpl->assign ("errormsg", "The specified forum could not be found or you do not have moderator priviledges in that forum.");
				}
			}
			
			$centreid = $this->model->getCentreId();
			
			$o =& Gene_Object::get($centreid);
			$forums = $o->getChilds(array(
				"where" => "type='forum'",
				"recursive" => true,
			));
			
			foreach ($forums as $i) {
				if (Gene_Object::checkPermission($i, "moderate")) {
					$rel[$i['parent']][] = $i;
				}
			}
			
			$tpl->assign ("centreid", $centreid);
			$tpl->assign ("forums", $rel);
			
			return $tpl->fetch ("objects/discussion/edit/move");
		}
	}
	
	/**
	 * Displays the object creation form for this type of object.
	 *
	 * @static
	 *
	 * @var object $parent Parent Object
	 *
	 * @return string HTML output for object creation.
	 */
	function create(&$parent) {
		$tpl =& Gene::getTemplate();
		
		// Popular Tags
		$set =& $parent->getTaxonomySet();
		$populartags = $set->getPopularLabels(50);
		if (count($populartags)) {
			foreach ($populartags as $j => $k) { // Reorder tags alphabetically
				$labels[$j] = $k['label'];
				$objects[$j] = $k['objects'];
			}
			array_multisort($labels, SORT_ASC, $populartags);
			
			$tpl->assign ("globaltags", $populartags);
		}
		
		// User Tags
		$userset =& $parent->getUserTaxonomySet();
		$tpl->assign ("usertags", $userset->getLabels());
		
		return $tpl->fetch("objects/discussion/create");
	}
	
	/**
	 * Creates the new object.
	 * 
	 * Objects can implement their own creation routines here to fiddle
	 * the user input before sending to Gene_Object::create() or return a
	 * PEAR::raiseError if input is invalid
	 */
	function doCreate($type, $title='', $desc='', $content='', &$parentobj, $options=array(), $draft=false) {
		$options['tags'] = explode(" ", Gene_Request::getString("tags", GENE_REQUEST_POST));
		
		return parent::doCreate($type, $title, $desc, $content, $parentobj, $options, $draft);
	}
	
	/**
	 * Calls web services
	 *
	 * Objects should implement XHR/JSON callback routines here.
	 */
	function callWebServices($method) {
		if ($method == "othertags") {
			$db =& Gene::getDatabase();
			$info = $this->model->get();
			
			$q = $db->prepare ("SELECT t.user_id, u.name, t.label FROM ".Gene::tableName("object_user_taxonomy")." t LEFT JOIN ".Gene::tableName("user_info")." u ON (t.user_id=u.user_id) WHERE t.set_id=? AND t.object_id=?");
			$res = $q->execute(array($info['parent'], $info['object_id']));
			
			$tags = array();
			
			while ($i = $res->fetchRow()) {
				$tags[$i['user_id']]['name'] = $i['name'];
				$tags[$i['user_id']]['tags'][] = $i['label'];
			}
			
			return array_values($tags);
		} elseif ($method == "savemytags") {
			$db =& Gene::getDatabase();
			$this->model->updateUserTags(explode(" ", Gene_Request::getString("tags", GENE_REQUEST_POST)));
			return array("success" => true);
		}
		
		return false;
	}
}
 
?>